package com.repair.category.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.repair.api.category.response.data.CategoryInfo;
import com.repair.category.mapper.ServiceCategoryMapper;
import com.repair.category.pojo.entity.ServiceCategory;
import com.repair.category.pojo.vo.ServiceCategoryVO;
import com.repair.category.service.ServiceCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务类型 服务实现类
 * </p>
 *
 * @author 桂龙
 * @since 2024-10-11
 */
@Service
public class ServiceCategoryServiceImpl extends ServiceImpl<ServiceCategoryMapper, ServiceCategory> implements ServiceCategoryService {
    @Autowired
    private ServiceCategoryMapper serviceCategoryMapper;

    @Override
    public List<ServiceCategoryVO> getAll() {
        // 1 查出所有分类
        List<ServiceCategoryVO> entities = serviceCategoryMapper.getAll();
        // 2 组装成父子的树形结构
        List<ServiceCategoryVO> level1Menus = entities.stream().filter(serviceCategoryVO ->
                serviceCategoryVO.getParentId().longValue() == 0
        ).map((menu) -> {
            menu.setChildren(getChildrens(menu, entities));
            return menu;
        }).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort()))).collect(Collectors.toList());
        return level1Menus;
    }

    @Override
    public CategoryInfo selectById(Long id) {
        CategoryInfo categoryInfo = serviceCategoryMapper.selectById(id);
        return categoryInfo;
    }

    /**
     * 递归查找所有菜单的子菜单
     */
    private List<ServiceCategoryVO> getChildrens(ServiceCategoryVO root, List<ServiceCategoryVO> all) {
        List<ServiceCategoryVO> children = all.stream().filter(serviceCategoryVO -> {
            return serviceCategoryVO.getParentId().longValue() == root.getId().longValue();  // 注意此处应该用longValue()来比较，否则会出先bug，因为parentCid和catId是long类型
        }).map(categoryEntity -> {
            // 1 找到子菜单
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            return categoryEntity;
        }).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort()))).collect(Collectors.toList());
        return children;
    }
}
